﻿using System.Reflection;
using System.Web.Http;
using Abp.Configuration.Startup;
using Abp.Modules;
using Abp.WebApi;
using Swashbuckle.Application;
using System.Linq;
using System;
using System.IO;
using FutureApp.Configuration;
using Abp.Application.Services;
using Newtonsoft.Json.Converters;

namespace FutureApp.Api
{
    /// <summary>
    /// API 注册模块
    /// </summary>
    [DependsOn(typeof(AbpWebApiModule), typeof(FutureAppApplicationModule))]
    public class FutureAppWebApiModule : AbpModule
    {
        private readonly static string WebPagesVersion = SettingsManager.GetAppSetting("webpages:Version");
        private readonly static string WebSiteAppName = SettingsManager.GetAppSetting("website:AppName");
        private readonly static string BinDirectoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin");
        private readonly static Assembly ThisAssembly = Assembly.GetExecutingAssembly();

        /// <inheritDoc/>
        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());
            //Dynamic Api
            Configuration.Modules.AbpWebApi().DynamicApiControllerBuilder
                .ForAll<IApplicationService>(typeof(FutureAppApplicationModule).Assembly, "app")
                .Build();

            if (SettingsManager.GetAppBooleanSetting("website:Debug"))
            {
                this.ConfigureSwaggerUi();
            }
        }

        /// <inheritDoc/>
        public override void PostInitialize()
        {
            var httpConfiguration = Configuration.Modules.AbpWebApi().HttpConfiguration;
            httpConfiguration.Filters.Add(IocManager.Resolve<ApiExceptionFilter>());
            httpConfiguration.Filters.Add(new HostAuthenticationFilter("Bearer"));
            httpConfiguration.Formatters.JsonFormatter.SerializerSettings
                .Converters.Insert(0, new IsoDateTimeConverter
                {
                    DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
                });
        }

        private void ConfigureSwaggerUi()
        {
            Configuration.Modules.AbpWebApi().HttpConfiguration
                .EnableSwagger(c =>
                {
                    c.SingleApiVersion(
                        version: WebPagesVersion,
                        title: "接口文档"
                    );
                    Directory.GetFiles(BinDirectoryPath, $"{WebSiteAppName}.*.xml")
                        .ToList().ForEach(file => c.IncludeXmlComments(file));
                    c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
                })
                .EnableSwaggerUi(c =>
                {
                    c.InjectStylesheet(ThisAssembly, "FutureApp.Api.Assets.Swagger.css");
                    c.InjectJavaScript(ThisAssembly, "FutureApp.Api.Assets.Swagger.js");
                });
        }
    }
}
